package com.key.win.business.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.key.win.base.auth.AuthenticationUtil;
import com.key.win.base.exception.BizException;
import com.key.win.base.page.MybatisPageServiceTemplate;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import com.key.win.business.chat.dao.ImGroupDao;
import com.key.win.business.chat.dao.ImGroupUserDao;
import com.key.win.business.chat.model.ImGroup;
import com.key.win.business.chat.model.ImGroupUser;
import com.key.win.business.chat.service.ImGroupUserService;
import com.key.win.business.chat.vo.ImGroupUserFullVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class ImGroupUserServiceImpl extends ServiceImpl<ImGroupUserDao, ImGroupUser> implements ImGroupUserService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ImGroupDao imGroupDao;

    public PageResult<ImGroupUser> findGroupUserByPaged(PageRequest<ImGroupUser> t) {
        MybatisPageServiceTemplate<ImGroupUser, ImGroupUser> query = new MybatisPageServiceTemplate<ImGroupUser, ImGroupUser>(this.baseMapper) {
            @Override
            protected AbstractWrapper constructWrapper(ImGroupUser groupUser) {
                return buildWrapper(groupUser);
            }
        };
        return query.doPagingQuery(t);
    }

    private AbstractWrapper buildWrapper(ImGroupUser imGroupUser) {
        if (imGroupUser == null) {
            logger.error("groupUser is null!");
            throw new IllegalArgumentException("好友为空！");
        }
//        if (StringUtils.isBlank(imGroupUser.getUserId())) {
//            logger.error("userId is null!");
//            throw new IllegalArgumentException("当前用户为空！");
//        }
        imGroupUser.setUserId(AuthenticationUtil.getUserId());
        LambdaQueryWrapper<ImGroupUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(imGroupUser.getGroupId())) {
            lambdaQueryWrapper.eq(ImGroupUser::getGroupId, imGroupUser.getGroupId());
        }
        // lambdaQueryWrapper.eq(ImGroupUser::getUserId, imGroupUser.getUserId());
        return lambdaQueryWrapper;
    }

    public List<ImGroupUser> findGroupUser(ImGroupUser imGroupUser) {
        return this.list(this.buildWrapper(imGroupUser));
    }

    public boolean addGroupUser(ImGroupUser imGroupUser) {
        if (imGroupUser == null) {
            logger.error("groupUser is null!");
            throw new IllegalArgumentException("组信息为空！");
        }
        if (StringUtils.isBlank(imGroupUser.getUserId())) {
            logger.error("userId is null!");
            throw new IllegalArgumentException("当前用户为空！");
        }
        if (StringUtils.isBlank(imGroupUser.getGroupId())) {
            logger.error("groupId is null!");
            throw new IllegalArgumentException("组信息为空！");
        }
        List<ImGroupUser> imGroupUsers = this.findGroupUser(imGroupUser);
        if (!CollectionUtils.isEmpty(imGroupUsers)) {
            logger.error("好友[{}]已是添加过了", imGroupUser.getUserId());
            throw new BizException("重复添加好友！");
        }
        return this.save(imGroupUser);
    }

    @Override
    public boolean batchAddGroupUser(ImGroupUser imGroupUser) {
        if (imGroupUser == null) {
            logger.error("groupUser is null!");
            throw new IllegalArgumentException("组信息为空！");
        }
        if (StringUtils.isBlank(imGroupUser.getGroupId())) {
            logger.error("groupId is null!");
            throw new IllegalArgumentException("组信息为空！");
        }
        if (CollectionUtils.isEmpty(imGroupUser.getUserIds())) {
            logger.error("userId list  is null!");
            throw new IllegalArgumentException("用户列表信息为空！");
        }
        ImGroup imGroup = imGroupDao.selectById(imGroupUser.getGroupId());
        if (imGroup == null) {
            logger.error("group is null!");
            throw new IllegalArgumentException("组不存在！");
        }
        if (this.baseMapper.deleteGrouUserByGroupId(imGroupUser.getGroupId()) >= 0) {
            List<ImGroupUser> imGroupUsers = new ArrayList<>();
            imGroupUser.getUserIds().forEach(userId -> {
                if (!imGroup.getUserId().equals(userId)) {
                    ImGroupUser groupUser = new ImGroupUser();
                    groupUser.setGroupId(imGroupUser.getGroupId());
                    groupUser.setUserId(userId);
                    imGroupUsers.add(groupUser);
                }
            });
            return this.saveBatch(imGroupUsers);
        }
        return Boolean.FALSE;
    }

    public boolean batchDelete(Set<String> ids) {
        return this.removeByIds(ids);
    }

    @Override
    public boolean updateGroupUser(ImGroupUser imGroupUser) {
        if (imGroupUser == null) {
            logger.error("groupUser is null!");
            throw new IllegalArgumentException("好友为空！");
        }
        if (StringUtils.isBlank(imGroupUser.getId())) {
            logger.error("groupUser Id is null!");
            throw new IllegalArgumentException("好友为空！");
        }
        ImGroupUser dbImGroupUser = this.getById(imGroupUser.getId());
        if (dbImGroupUser == null) {
            logger.error("没有找到id[]的好友信息！", imGroupUser.getId());
            throw new BizException("好友不存在！");
        }
        dbImGroupUser.setName(imGroupUser.getName());
        dbImGroupUser.setGroupId(imGroupUser.getGroupId());
        return this.saveOrUpdate(dbImGroupUser);
    }

    public List<ImGroupUser> findGroupUserByUserId(String userId) {
        ImGroupUser f = new ImGroupUser();
        f.setUserId(userId);
        return this.findGroupUser(f);
    }

    @Override
    public List<ImGroupUserFullVo> findGroupUserByGroupId(String groupId) {
        if (StringUtils.isBlank(groupId)) {
            logger.error("groupUser groupId is null!");
            throw new IllegalArgumentException("组Id为空！");
        }
        LambdaQueryWrapper<ImGroupUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ImGroupUser::getGroupId, groupId);
        return this.baseMapper.findMyGroupUser(lambdaQueryWrapper);
    }

    @Override
    public int deleteGrouUserByGroupId(String groupId) {
        return this.baseMapper.updateEnableFlagByGroupId(groupId);
    }
}
